package com.situ.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.bean.Project;
import com.situ.mapper.ProjectMapper;
import com.situ.mapper.WorkMapper;
import com.situ.service.ProjectService;

@Service
public class ProjectServiceImpl implements ProjectService {

	@Autowired
	private ProjectMapper projectMapper;
	@Autowired
	private WorkMapper workMapper;

	@Override
	@Transactional
	public Project add(Project project) {
		// 事务管理
		// 1 保存项目
		projectMapper.insert(project);

		// 2 保存项目与员工的关联
		workMapper.batchInsert(project.getId(), project.getStaffs());

		return projectMapper.selectByPrimaryKey(project.getId());
	}

	@Override
	@Transactional
	public Project remove(Integer id) {
		// 查询项目
		Project project = projectMapper.selectByPrimaryKey(id);

		// 删除项目
		projectMapper.deleteByPrimaryKey(id);

		// 删除人员的关联
		workMapper.deleteByProjectId(id);
		return project;
	}

	@Override
	@Transactional
	public Project edit(Project project) {

		// 1 修改项目
		projectMapper.updateByPrimaryKey(project);
		// 2 修改Work
		// 2.1 删除原有的关联
		workMapper.deleteByProjectId(project.getId());
		// 2.2 重新添加新的关联
		workMapper.batchInsert(project.getId(), project.getStaffs());
		// 3 查询项目
		return projectMapper.selectByPrimaryKey(project.getId());
	}

	@Override
	public Project getById(Integer id) {
		return projectMapper.selectByPrimaryKey(id);
	}

	@Override
	public PageInfo getByPage(Integer page, Integer limit, Project project) {
//		if (page == null)
//			page = 1;
//		if (limit == null) {
//			List<Project> projects = projectMapper.select(project);
//			limit = projects.size();
//		}
		// 1开启分页
		PageHelper.startPage(page, limit);
		// 调用查询
		List<Project> projects = projectMapper.select(project);
		//
		PageInfo pageInfo = new PageInfo<>(projects);

		return pageInfo;
	}

}
